package games.gong.durid.controller;

import games.gong.durid.common.R;
import games.gong.durid.common.PermissionConstants;
import games.gong.durid.dto.UserDTO;
import games.gong.durid.entity.User;
import games.gong.durid.service.UserService;
import games.gong.durid.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户相关的增删改查操作")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Operation(summary = "创建用户")
    @PostMapping
    @PreAuthorize("@ss.hasPermission('" + PermissionConstants.USER_CREATE + "')")
    public R<UserVO> createUser(
            @Parameter(description = "用户信息") @RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 密码加密应该在Service层完成
        int result = userService.addUser(user);
        if (result > 0) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return R.success("用户创建成功", userVO);
        } else {
            return R.error("用户创建失败");
        }
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('" + PermissionConstants.USER_DELETE + "')")
    public R<String> deleteUser(
            @Parameter(description = "用户ID") @PathVariable Long id) {
        int result = userService.deleteUser(id);
        if (result > 0) {
            return R.success("用户删除成功");
        } else {
            return R.error("用户删除失败");
        }
    }

    @Operation(summary = "更新用户")
    @PutMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('" + PermissionConstants.USER_UPDATE + "')")
    public R<UserVO> updateUser(
            @Parameter(description = "用户ID") @PathVariable Long id,
            @Parameter(description = "用户信息") @RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setId(id);
        user.setUpdateTime(LocalDateTime.now());
        // 密码加密应该在Service层完成
        int result = userService.updateUser(user);
        if (result > 0) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return R.success("用户更新成功", userVO);
        } else {
            return R.error("用户更新失败");
        }
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('" + PermissionConstants.USER_READ + "')")
    public R<UserVO> getUser(
            @Parameter(description = "用户ID") @PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return R.success(userVO);
        } else {
            return R.error("用户不存在");
        }
    }

    @Operation(summary = "获取所有用户")
    @GetMapping
    @PreAuthorize("@ss.hasPermission('" + PermissionConstants.USER_READ + "')")
    public R<List<UserVO>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        List<UserVO> userVOs = users.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        return R.success(userVOs);
    }
}